import useDefine from "./build/define";
import usePlugins from "./build/plugins";
import { defineConfig, ConfigEnv, loadEnv } from "vite";

export default defineConfig(({ command, mode }: ConfigEnv) => {
  const root = process.cwd();
  const {
    VITE_USE_MOCK,
    VITE_BUILD_COMPRESS,
    VITE_APP_TITLE,
    VITE_OCCUPY_VISUALIZATION,
  } = loadEnv(mode, root);

  const isBuild = command === "build";

  return {
    base: isBuild ? "./" : "/",
    resolve: {
      alias: {
        "@": "/src",
        "@build": "/build",
      },
    },
    define: useDefine(), //定义全局常量替换方式。其中每项在开发环境下会被定义在全局，而在构建时被静态替换
    plugins: usePlugins({
      isBuild,
      //mock文档
      isMock: VITE_USE_MOCK === "true",
      //打包压缩
      compress: VITE_BUILD_COMPRESS,
      title: VITE_APP_TITLE,
      //开启可视化占用
      occupy: VITE_OCCUPY_VISUALIZATION === "true",
    }),
    esbuild: {
      drop: mode === "development" ? [] : ["console", "debugger"], //在编译时取消console和debugger
    },

    build: {
      //打包的 js版本
      target: "es2015",
      //打包的 css版本
      cssTarget: "chrome80",
      //禁用 gzip 压缩大小报告  会提高大型项目的构建性能
      reportCompressedSize: false,
      //多少大小的chunk触发警报
      chunkSizeWarningLimit: 1500,
      //自定义底层的 Rollup 打包配置
      rollupOptions: {
        output: {
          // 入口文件名
          entryFileNames: "assets/[name].js",
          //代码分割
          manualChunks: {
            vue: ["vue", "pinia", "vue-router"],
            elementPls: ["element-plus"],
          },
        },
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          // additionalData:`@import '@/assets/less/index.less';`
        },
      },
    },
    server: {
      //指定服务器应该监听哪个 IP 地址
      host: true, //将监听所有地址 包括局域网和公网地址
    },
  };
});
